package org.lv.learning.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.lv.learning.entity.Storage;
import org.lv.learning.mapper.StorageMapper;
import org.lv.learning.service.IStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 *
 */
@Service
public class StorageServiceImpl implements IStorageService {

    @Autowired
    private StorageMapper storageMapper;

    @Override
    public Integer deduct(Long productId, Integer count) {

        Storage storage = storageMapper.selectById(productId);

        if(ObjectUtil.isNull(storage)){
            throw new RuntimeException("产品不存在");
        }

        LambdaUpdateWrapper<Storage> queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.eq(Storage::getProductId, productId);
        queryWrapper.gt(Storage::getNum, count);
//        queryWrapper.set(Storage::getNum, sub.intValue());
        queryWrapper.setSql("num = num - " + count);
        int update = storageMapper.update(null, queryWrapper);

        if(update == 0){
            throw new RuntimeException("库存不足");
        }

        return update;
    }
}
